﻿/*
 * @author Lee 
 * Time: 20180403 
 * Abstract: SharePoint API的二次封装
 */

using System;
using Microsoft.SharePoint;
using System.IO;

namespace SharePointHelper.DLL.SSOM
{
	public class Library
	{
        #region 获取 Document Library URL 
        /// <summary>
        /// 获取 Document Library URL (w/o trailing slash)
        /// </summary>
        /// <param name="library"></param>
        /// <returns></returns>
        public static string GetUrl(SPDocumentLibrary library, bool isAbsoluteUrl)
		{
			return List.GetUrl(library, isAbsoluteUrl);
		}

		/// <summary>
		/// 获取 document library url (w/o trailing slash)
		/// </summary>
		/// <param name="library"></param>
		/// <returns></returns>
		public static string GetUrl(SPDocumentLibrary library)
		{
			return GetUrl(library, false);
		}
        #endregion

        #region 通过library uniqueId获取 Docment Library
        /// <summary>
        ///  通过library uniqueId获取 Docment Library
        /// </summary>
        /// <param name="web"></param>
        /// <param name="libraryId"></param>
        /// <returns></returns>
        public static SPDocumentLibrary GetLibraryById(SPWeb web, Guid libraryId)
		{
			SPDocumentLibrary library = null;
			try
			{
				// 初始化
				if (web == null) { web = Web.GetWeb(); }
				if (web == null) { throw new Exception("SPWeb passed is null or can't get from SPContext"); }
				if (libraryId == null || libraryId == Guid.Empty) { throw new Exception("Invalid libraryId passed"); }

				// 获取 document library
				if (web.Lists.Count > 0)
				{
					foreach (SPList _list in web.Lists)
					{
						if (_list.ID == libraryId) { library = _list as SPDocumentLibrary; break; }
					}
				}

			}
			catch (Exception ex)
			{
				Log.WriteError("yjdd8l6utHHfgfgr5", ex, " libraryId: " + libraryId);
				library = null;
			}
			return library;
		}        

        public static SPDocumentLibrary GetLibraryById(Guid libraryId)
		{
			return GetLibraryById(null, libraryId);
		}
        #endregion

        #region 通过title获取document library 
        /// <summary>
        /// 通过title获取document library 
        /// </summary>
        /// <param name="web"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        public static SPDocumentLibrary GetLibraryByTitle(SPWeb web, string title)
		{
			SPDocumentLibrary library = null;
			try
			{
				// 初始化
				if (web == null) { web = Web.GetWeb(); }
				if (web == null) { throw new Exception("SPWeb passed is null or can't get from SPContext"); }
				if (string.IsNullOrEmpty(title)) { throw new Exception("Title passed is null"); }
				title = title.Trim();


				// 获取 document library
				if (web.Lists.Count > 0)
				{
					library = web.Lists.TryGetList(title) as SPDocumentLibrary;
				}

			}
			catch (Exception ex)
			{
				Log.WriteError("87trlyGfuGGtrtrt78jg", ex, "title: " + title);
				library = null;
			}
			return library;
		}
        #endregion

        #region 通过URL获取document library
        /// <summary>
        /// 通过URL获取document library
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static SPDocumentLibrary GetLibraryByUrl(string url)
		{
			SPDocumentLibrary library = null;
			try
			{
				// 获取 list
				library = List.GetListByUrl(url) as SPDocumentLibrary;
			}
			catch (Exception ex)
			{
				// Log.WriteError("tyfhdgdsxrgsd5yrdruy", ex, "document library url: " + url);
				library = null;
			}
			return library;
		}       

        public static SPDocumentLibrary GetLibraryByUrl(SPWeb web, string url)
		{
			SPDocumentLibrary library = null;
			try
			{
				// get list
				library = List.GetListByUrl(web, url) as SPDocumentLibrary;
			}
			catch (Exception ex)
			{
				// Log.WriteError("tyfhdry6ejtfgsd5yrdruy", ex, "document library url: " + url);
				library = null;
			}
			return library;
		}
        #endregion

        #region 创建一个Docunment library
        /// <summary>
        /// 创建一个Docunment library
        /// </summary>
        /// <param name="web"></param>
        /// <param name="title"></param>
        /// <param name="description"></param>
        /// <param name="isForceCheckOut"></param>
        /// <param name="isEnableVersioning"></param>
        /// <param name="majorVersionLimit"></param>
        /// <param name="isEnableMinorVersions"></param>
        /// <param name="majorWithMinorVersionsLimit"></param>
        /// <param name="isOnQuickLaunch"></param>
        /// <param name="documentTemplateStream"></param>
        /// <param name="documentTemplateByteArray"></param>
        /// <param name="documentTemplateFilename"></param>
        /// <param name="newDefaultContentType"></param>
        /// <param name="isThrowErrorIfAlreadyExists"></param>
        /// <returns></returns>
        public static SPDocumentLibrary CreateOne(SPWeb web, string title, string description,
			bool isForceCheckOut, bool isEnableVersioning, int? majorVersionLimit, bool isEnableMinorVersions,
			int? majorWithMinorVersionsLimit, bool isOnQuickLaunch, MemoryStream documentTemplateStream,
			byte[] documentTemplateByteArray, string documentTemplateFilename, SPContentType newDefaultContentType,
			bool isThrowErrorIfAlreadyExists)
		{
			SPDocumentLibrary library = null;
			try
			{
				// 初始化
				if (web == null) { throw new Exception("SPWeb passed is null"); }
				if (string.IsNullOrEmpty(title)) { throw new Exception("No library title passed"); }
				if (documentTemplateByteArray != null && documentTemplateStream != null)
				{ throw new Exception("Both document template stream and document template byte array cannot be defined"); }
				if ((documentTemplateStream != null || documentTemplateByteArray != null) && string.IsNullOrEmpty(documentTemplateFilename))
				{ throw new Exception("Document template stream or byte array defined, but filename not defined"); }
				bool isAddTemplate = false;
				if (documentTemplateStream != null || documentTemplateByteArray != null) { isAddTemplate = true; }


				// 判断 list 是否已经存在
				SPList list = web.Lists.TryGetList(title);
				if (list != null)
				{
					if (isThrowErrorIfAlreadyExists) { throw new Exception("Cannot create document library b/c list with same name already exists"); }
				}
				else
				{
					Guid libraryId = web.Lists.Add(title, description, SPListTemplateType.DocumentLibrary);
					library = (SPDocumentLibrary)web.Lists[libraryId];

					library.Title = title;
					library.ForceCheckout = isForceCheckOut;
					library.EnableVersioning = isEnableVersioning;
					if (majorVersionLimit != null) { library.MajorVersionLimit = (int)majorVersionLimit; }
					library.EnableMinorVersions = isEnableMinorVersions;
					if (majorWithMinorVersionsLimit != null) { library.MajorWithMinorVersionsLimit = (int)majorWithMinorVersionsLimit; }
					library.OnQuickLaunch = isOnQuickLaunch;

					// 是否添加默认模板
					if (isAddTemplate)
					{
						SPFolder formsFolder = library.RootFolder.SubFolders["Forms"];
						if (formsFolder == null || !formsFolder.Exists) { throw new Exception("Failed to get Forms folder from newly created doc lib: " + title); }
						SPFile template = null;

						if (documentTemplateStream != null) { template = formsFolder.Files.Add(documentTemplateFilename, documentTemplateStream); }
						else if (documentTemplateByteArray != null) { template = formsFolder.Files.Add(documentTemplateFilename, documentTemplateByteArray); }

						if (template == null || !template.Exists) { throw new Exception("Failed to create document template: " + documentTemplateFilename); }
						if (title.Substring(title.Length - 2, 1) == "/") { title = title.Substring(0, title.Length - 1); }
						library.DocumentTemplateUrl = title + "/Forms/" + documentTemplateFilename;
					}

					// 是否设置默认content type?
					if (newDefaultContentType != null)
					{
						// allow content types
						library.ContentTypesEnabled = true;
						library.Update();

						// reference content type
						library.ContentTypes.Add(newDefaultContentType);

						// delete Item content type
						library.ContentTypes["Document"].Delete();
					}

					// 执行
					library.Update();
				}
			}
			catch (Exception ex)
			{
				Log.WriteError("aerygj6uww46fhsdfds", ex, "title: " + title);
				library = null;
			}
			return library;
		}
        #endregion

        #region 删掉一个library里面的所有documents
        /// <summary>
        /// 删掉一个library里面的所有documents
        /// To delete items, use the Item.DeleteAllItems member
        /// 不会删掉 checked out items
        /// 不会删掉默认的 homepage from Pages library
        /// http://msdn.microsoft.com/en-us/library/ms461938.aspx
        /// http://social.technet.microsoft.com/Forums/en-US/sharepoint2010customization/thread/e0eefd6b-e954-46d8-9c49-703de6eda592
        /// </summary>
        /// <param name="library"></param>
        /// <returns></returns>
        public static bool DeleteAllFiles(SPDocumentLibrary library, bool isDisableRecycleBin)
		{
			return Item.DeleteAllItems(library, isDisableRecycleBin);
		}
        #endregion
    }
}
